/*
 * Copyright (C) 2010 TopCoder Inc., All Rights Reserved.
 */
package com.hercules.xre.protocol.testing.handlers.imageserializer;

import com.hercules.xre.protocol.testing.handlers.Helper;
import com.hercules.xre.protocol.testing.handlers.ImageSerializer;
import com.hercules.xre.protocol.testing.handlers.ImageSerializerException;

import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

/**
 * This is default implementation of {@link ImageSerializer} that utilizes built-in {@link ImageIO} Java class to
 * perform the serialization.
 * <p>
 * <b>Thread safety:</b> This class is thread safe since it is stateless.
 *
 * @author bramandia, 7realm
 * @version 1.0
 */
public class ImageIOImageSerializer implements ImageSerializer {
    /**
     * Empty constructor.
     */
    public ImageIOImageSerializer() {
        // empty default constructor
    }

    /**
     * Save the given image with the given output file to the given filename.
     *
     * @param image the image to save, must not be null
     * @param outputFormat the output type (e.g. "png", "jpg", etc), must not be null/empty.
     * @param filename the output filename to save to, must not be null/empty
     * @throws IllegalArgumentException if any argument is invalid
     * @throws ImageSerializerException if there is any error occurred during image serialization
     */
    public void serializeImage(BufferedImage image, String outputFormat, String filename)
        throws ImageSerializerException {
        // check argument
        Helper.checkNull(image, "image");
        Helper.checkString(outputFormat, "outputFormat");
        Helper.checkString(filename, "filename");

        try {
            OutputStream fileOutputStream = new FileOutputStream(filename);
            try {
                ImageIO.write(image, outputFormat, fileOutputStream);
            } finally {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            throw new ImageSerializerException("Error occurred while serializing image to file '" + filename
                + "', output format '" + outputFormat + "'.", e);
        }
    }
}
